package com.hengtiansoft.lfy.chart.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.GetUserJson;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.getUserByUsernameBean;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.widget.AlertDialog;
import com.hengtiansoft.lfy.widget.CodeDialog;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hyphenate.chat.EMClient;
import com.squareup.picasso.Picasso;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

/**
 * 联系人详情
 */
public class PersonalDetailsActivity extends BaseActivity implements
        OnClickListener {
    private static String TAG = "PersonalDetailsActivity";
    private Context mContext;
    private ProgressDialog pd;
    private ImageView mIvAvatar;
    private ImageView mIvSex;
    private RelativeLayout mRlSend;
    private TextView mTvNickname;
    private TextView mTvUsername;
    private TextView mTvSignature;
    private TextView mTvSend;
    private ImageView mIvBack;
    private RelativeLayout mRlBarcode;
    private String username;
    private String nickname;
    private String sex;
    private String type;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        mContext = this;
        setContentView(R.layout.activity_personal_details);
        initView();
        initListener();
    }

    private void initView() {
        username = getIntent().getStringExtra("username");
        type = getIntent().getStringExtra("type");
        mTvSignature = (TextView) findViewById(R.id.tv_signature);
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mIvAvatar = (ImageView) findViewById(R.id.iv_personal_img);
        mIvSex = (ImageView) findViewById(R.id.iv_sex);
        mTvSend = (TextView) findViewById(R.id.tv_me_send);
        if (type.equals("send")) {
            mTvSend.setText(getString(R.string.personal_details_send));
        } else {
            mTvSend.setText(getString(R.string.add_friend2));
        }
        mRlSend = (RelativeLayout) findViewById(R.id.rl_me_send);
        mTvNickname = (TextView) findViewById(R.id.tv_nickname);
        mTvUsername = (TextView) findViewById(R.id.tv_username);
        mRlBarcode = (RelativeLayout) findViewById(R.id.rl_barcode);
        pd = new ProgressDialog(PersonalDetailsActivity.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage(getString(R.string.picture_image_loading));
        pd.show();
        if (username != null) {
            GetUserJson getUserJson = new GetUserJson(Config.getUserToken(), username);
            getUserByUsernameRequest(Constants.getUserByUsername, getUserJson);//网络请求获取用户信息并且更新界面
        }
    }

    private void initListener() {
        mIvBack.setOnClickListener(this);
        mRlSend.setOnClickListener(this);
        mRlBarcode.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//        case R.id.user_head_avatar:
//            break;
        case R.id.rl_nickname:
            break;
        case R.id.rl_me_send:
            if (type.equals("send")) {
                if (Config.getUserName().toLowerCase().equals( username)) { //判断是否是自己
                    Toast.makeText(this, getString(R.string.Cant_chat_with_yourself), Toast.LENGTH_SHORT).show();
                    return;
                }
                if(ContactlistActivity.getActivity()!=null){
                    ContactlistActivity.getActivity().finish();
                }
                startActivity(new Intent(mContext, ChatActivity.class)
                        .putExtra("userId", mTvUsername.getText().toString()));
                finish();
            } else {
                addContact(username);
            }
            break;
        case R.id.iv_back:
            finish();
            break;
        case R.id.rl_barcode:
            final CodeDialog codeDialog = new CodeDialog(mContext, username,
                    nickname, sex);
            codeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            codeDialog.show();
            break;
        default:
            break;
        }

    }

    /**
     * 添加contact
     * 
     * @param
     */
    public void addContact(final String name) {
        if (Config.getUserName().toLowerCase().equals(name)) { //判断是否是自己
            String str = getString(R.string.not_add_myself);
            startActivity(new Intent(this, AlertDialog.class).putExtra("msg",
                    str));
            return;
        }

        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList()
                .containsKey(name)) { //判断是否有此好友
            // 提示已在好友列表中，无需添加
            if (EMClient.getInstance().contactManager().getBlackListUsernames()
                    .contains(name)) {  //是否在黑名单列表
                startActivity(new Intent(this, AlertDialog.class).putExtra(
                        "msg", getString(R.string.is_your_friend)));
                return;
            }
            String strin = getString(R.string.This_user_is_already_your_friend);
            startActivity(new Intent(this, AlertDialog.class).putExtra("msg",
                    strin));
            return;
        }

        progressDialog = new ProgressDialog(PersonalDetailsActivity.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    // demo写死了个reason，实际应该让用户手动填入
                    String s = getResources().getString(R.string.Add_a_friend);
                    EMClient.getInstance().contactManager().addContact(name, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(
                                    R.string.send_successful);
                            Toast.makeText(getApplicationContext(), s1, 1)
                                    .show();
                            startActivity(new Intent(mContext,
                                    ContactlistActivity.class));
                            finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(
                                    R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(),
                                    s2 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }

    private  void getUserByUsernameRequest(String getUserByUsername,
            GetUserJson mGetUserJson) {
        Log.i(TAG,
                "<getUserByUsernameRequest>--<onResponse>--上传的JSon数据：  GetUserJson = "
                        + mGetUserJson);
        Type type = new TypeToken<BaseResult<getUserByUsernameBean>>() {
        }.getType();//post_url http://115.231.106.179/lfy-api/getUserByUsername/
        JsonListRequest<BaseResult<getUserByUsernameBean>> request = new JsonListRequest<BaseResult<getUserByUsernameBean>>(
                mContext, Method.POST, getUserByUsername,
                mGetUserJson.toString(), null, null, type, false,
                new Listener<BaseResult<getUserByUsernameBean>>() {

                    @Override
                    public void onResponse(
                            BaseResult<getUserByUsernameBean> arg0) {
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        getUserByUsernameBean data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        if (code == 0) {
                            data = arg0.getData();
                            if (data != null) {
                                mTvUsername.setText(data.getUsername());
                                if (null == data.getNickname()
                                        || data.getNickname().equals("")) {
                                    mTvNickname.setText(data.getUsername());
                                    nickname = data.getUsername();
                                } else {
                                    nickname = data.getNickname();
                                    mTvNickname.setText(data.getNickname());
                                }
                                sex = data.getSex();
                                if (sex != null) {
                                    if (sex.equals("f")) { //性别
                                        mIvSex.setImageResource(R.drawable.sex_girl);
                                    } else if (sex.equals("m")) {
                                        mIvSex.setImageResource(R.drawable.me_sex);
                                    } else {
                                        mIvSex.setVisibility(View.GONE);
                                    }
                                } else {
                                    mIvSex.setVisibility(View.GONE);
                                }
                                if(data.getImagepath()!=null&&!"".equals(data.getImagepath())){
                                    Picasso.with(mContext)
                                            .load(Constants.GETIMAGE+data.getImagepath())
                                            .placeholder(R.drawable.default_avatar).into(mIvAvatar);
                                }else{
                                    Picasso.with(mContext).load(R.drawable.default_avatar)
                                            .into(mIvAvatar);
                                }
                                /*if (data.getUsername().equals(
                                        LfyApplication.getInstance()
                                                .getUserName())) {
                                    UserUtils.setCurrentUserAvatar(mContext,
                                            mIvAvatar);
                                } else {
                                    UserUtils.setUserAvatar(mContext,
                                            data.getUsername(), mIvAvatar);
                                }*/
                                if (data.getSignature() != null) { //个性签名
                                    mTvSignature.setText(data.getSignature());
                                } else {
                                    mTvSignature.setText(getString(R.string.signature));
                                }

                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        pd.dismiss();
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser
                                                .parseCharset(response.headers));
                                Log.i(TAG,
                                        "<getUserByUsernameRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<getUserByUsernameRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<getUserByUsernameRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null
                                && arg0.toString().contains(
                                        "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null
                                && arg0.toString().contains(
                                        "com.android.volley.ServerError")) {
                            Toast.makeText(
                                    mContext,
                                    getString(R.string.service_temporarily_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null
                                && arg0.toString().contains(
                                        "com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                        pd.dismiss();
                    }

                });
        VolleyUtil.addRequest(request);
    }
}
